<style lang='scss'>

</style>
<template>
	<div>
        <compWrapper title="授权分配">
            <div style="padding: 10px">
                <Form class="clearfix margin-top-15" :label-width="140"  ref="form" :model='formData'>
                    <Row v-if="!isOther">
                        <Col span="6">
                            <FormItem prop='carrierCode' label="Carrier" :rules="required">
                                {{ formData.carrierCode }}
                            </FormItem>
                        </Col>
                        <Col span="8">
                            <FormItem prop='accountId' label="账号别名" :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.accountId" clearable filterable>
                                    <Option v-for="item in accountList" :key="item.value" :value="item.value">{{item.label}}</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{formData.accountName}}</div>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row v-if="!isOther">
                        <Col span="6">
                            <FormItem prop='billType' label="Bill Type" :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.billType" @on-change="changeBillType">
                                    <Option :value="0">Bill Sender</Option>
                                    <Option :value="1">3rd Party</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{formData.billType == 0 ? 'Bill Sender' : '3rd Party'}}</div>
                            </FormItem>
                        </Col>
                        <Col v-if="formData.billType == 1" span="8" >
                            <FormItem prop='thirdPartyAccount' label="ThirdPartyAccount" :rules="required">
                                <Input v-if="type !== 'query'" v-model="formData.thirdPartyAccount" placeholder="输入3rd party 账号"/>
                                <div v-else style="line-height: 34px">{{formData.thirdPartyAccount}}</div>
                            </FormItem>
                        </Col>
                        <div v-if="formData.billType == 1" style="padding-top: 5px; font-size: 16px;" class="margin-left-10">
                            <Tooltip max-width="230" placement="top" content="3rd账号不能开启SMART POST服务"><Icon type="md-help-circle" /></Tooltip>
                        </div>
                        <Col v-if="formData.billType == 1 && isUPS" span="6" >
                            <FormItem prop='billThirdPartyCountry' label="Bill3rdpartyCountry" :rules="required">
                                <Input v-if="type !== 'query'" v-model="formData.billThirdPartyCountry" placeholder="请输入"/>
                                <div v-else style="line-height: 34px">{{formData.billThirdPartyCountry}}</div>
                            </FormItem>
                        </Col>
                        <Col v-if="formData.billType == 1 && isUPS" span="6" >
                            <FormItem prop='billThirdPartyPostal' label="Bill3rdpartyPostal" :rules="required">
                                <Input v-if="type !== 'query'" v-model="formData.billThirdPartyPostal" placeholder="请输入"/>
                                <div v-else style="line-height: 34px">{{formData.billThirdPartyPostal}}</div>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row v-else>
                        <Col span="6">
                            <FormItem prop='serviceCode' label="物流产品" :rules="required">
                                {{ formData.serviceCode }}
                            </FormItem>
                        </Col>
                        <Col span="6">
                            <FormItem prop='carrierType' label="CarrierType" :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.carrierType" >
                                    <Option :value="0">快递</Option>
                                    <Option :value="1">卡车</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{ formData.carrierType == 0 ? '快递' : '卡车' }}</div>
                            </FormItem>
                        </Col>
                        <Col span="6">
                            <FormItem prop='carrierCode' label="Carrier" :rules="required">
                                <Input v-if="type !== 'query'" v-model="formData.carrierCode" placeholder="请输入"/>
                                <div v-else style="line-height: 34px">{{ formData.carrierCode}}</div>
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="6">
                            <FormItem prop='serviceType' label="分配Label/仓库" :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.serviceType" @on-change="changeLabel">
                                    <Option :value="0">Label</Option>
                                    <Option :value="1">仓配</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{ formData.serviceType == 0 ? 'Label' : '仓配' }}</div>
                            </FormItem>
                        </Col>
                        <Col v-if="formData.serviceType == 0" span="6">
                            <FormItem prop='organizationId' label="客户组织" :rules="required" >
                                <Select v-if="type !== 'query'" v-model="formData.organizationId" @on-change="getShipCodeList" clearable filterable>
                                    <Option v-for="item in chooseOrgList" :key="item.value" :value="item.value">{{item.label}}</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{formData.orgName}}</div>
                            </FormItem>
                        </Col>
                        <Col v-if="formData.serviceType == 0" span="6">
                            <FormItem prop='serviceRefCode' label="Ship Code" clearable filterable :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.serviceRefCode" clearable filterable>
                                    <Option v-for="item in shipCodeList" :key="item.value" :value="item.value">{{item.label}}</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{formData.serviceRefCode}}</div>
                            </FormItem>
                        </Col>
                        <Col v-if="formData.serviceType == 0 && type !== 'query'" span="2">
                            <div style="margin-left: 20px; padding-top: 8px">
                                <a @click="addAddress">添加</a>
                            </div>
                        </Col>
                        <Col v-if="formData.serviceType == 1 || formData.serviceType == 2" span="6">
                            <FormItem prop='serviceRefCode' label="仓库" :rules="required">
                                <Select v-if="type !== 'query'" v-model="formData.serviceRefCode" filterable clearable>
                                    <Option v-for="item in getAdminTransferWarehouse" :key="item.id" :value="item.value">{{item.label}}</Option>
                                </Select>
                                <div v-else style="line-height: 34px">{{formData.serviceRefCode}}</div>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div>
                <Table v-if="!isOther" class="margin-15" max-height="370" :columns="serviceColumns" :data="serviceList" border @on-selection-change="handleChooseService"></Table>
                <div v-else style="display:flex">
                    <Table class="margin-15" width="1000" :columns="serviceColumnsOther" :data="serviceListOther" border ></Table>
                    <Button v-if="type == 'add'" class="margin-15" @click="addOtherService">添加一行</Button>
                </div>
            </div>
        </compWrapper>
        <compWrapper title="操作历史" v-if=" type === 'query' ">
			<compLog class="margin-15" :data="opLogList" :columns="logcolumn"></compLog>
		</compWrapper>
		<div v-if="type!='query'" class="text-right margin-top-10">
			<Button type="primary" @click="submit">保存</Button>
			<Button class="margin-left-10" @click="onCancel">返回</Button>
		</div>
        <compModal
			v-model="modalProps.show"
			v-bind="modalProps"
            @on-close="closemodalprops"
		>
            <component ref="cusref" :is="modalProps.component"  v-bind="modalProps" @on-close="closemodalprops" v-on="modalProps.on"></component>
        </compModal>
		<Spin v-if="loading" fix></Spin>
	</div>
</template>

<script>
import {  HttpCarrierAccountDetail, HttpCarrierAccountSave, HttpSysCarrierServiceList, HttpShipCodeList, HttpOrgList, HttpGetSysAccountList } from '@/service/api/views';
import { mapGetters } from "vuex";
import mixins from '../mixin'
import { h,resolveComponent } from 'vue'
import compAddress from '../shippingaddress/update.vue';

export default {
	props:['querytype','activeid'],
    mixins: [ mixins ],
    components: {
        compAddress,
    },
	data() {
		return {
            type: this.querytype || this.$route.params.type,
            id: this.activeid || this.$route.query.id,
            carrierId: this.$route.query.carrierId,
            carrierGroupId: this.$route.query.carrierGroupId,
            loading: false,
            formData: {
                serviceType: 0,
            },
            required: [{
                required: true,
                message: "该信息不能为空,请填写"
            }],
            opLogList: [],
            serviceList: [],
            serviceListOther: [
                {carrierServiceCode: '', isLabel: false},
            ],
            modalProps:{
                show:false
            },
            chooseServiceList: [],
            shipCodeList: [],
            otherServiceList: [],
            chooseOrgList: [],
            accountList: [],
		};
	},
	async created() {
        await HttpGetSysAccountList({'search[EQ_active]': 1, 'search[EQ_carrierId]': this.carrierId}).then(res=>{
            this.accountList = res.data.map(item=>{
                return {
                    value: item.id,
                    label: item.accountName,
                    attach: item
                }
            })
        })
        await HttpOrgList().then(res=>{
            if(res.data){
                this.chooseOrgList = res.data.map(item=>{
                    return {
                        value: item.id,
                        label: item.name,
                        attach: item
                    }
                })
            }
            this.getDetail();
        })
	},
	computed: {
         ...mapGetters('dictionary',['getSysAllList', 'getAdminTransferWarehouse','getBillcusorgList']),
        isFedEx() {
            return this.formData.carrierCode == 'FedEx';
        },
        isUPS() {
            return this.formData.carrierCode == 'UPS';
        },
        isOther() {
            return this.formData.carrierCode !== 'FedEx' && this.formData.carrierCode !== 'UPS';
        },
        serviceColumns(){
            let arr =[
                {
                    type: 'selection',
                    key: 'id',
                    width: 60,
                },
                {
                    title: "Service Code",
                    key: "carrierServiceCode",
                },
                {
                    title: "体积重系数",
                    key: "volumeWeight",
                    render: ( h, {row, index}) =>{
                        if (this.type !== 'query') {
                            return h(resolveComponent('InputNumber'), {
                                min: 0,
                                modelValue: row.volumeWeight || 0,
                                "onOn-change":(event) => {
                                    row.volumeWeight = event;
                                    this.serviceList[index] = row;
                                    }
                                },
                        )} else {
                          return <div>{row.volumeWeight}</div>
                        }
                    },
                    width: 250,
                },
                {
                    title: "是否测算",
                    key: "isCalculate",
                    render:(h,{row, index})=>{
                        if (this.type !== 'query') {
                            return h(resolveComponent('Checkbox'), {
                                modelValue: row.isCalculate || false,
                                "onOn-change":(event) => {
                                    row.isCalculate = event;
                                    this.serviceList[index] = row;
                                    }
                                },
                        )} else {
                          return <div>{row.isCalculate ? '是' : '否'}</div>
                        }
                    },
                    align: 'center',
                    width: 120,
                },
                {
                    title: "Transit Time",
                    key: "remark",
                    render:(h,{row})=>{
                        return <div>{row.remark || '--'}</div>
                    }
                },
            ]
            return this.type == 'query' ? arr.slice(1) : arr;
        },
        serviceColumnsOther(){
            return [
                {
                    title: "Service Code",
                    key: "carrierServiceCode",
                    render: ( h, {row, index}) =>{
                        if (this.type == 'add') {
                            return h(resolveComponent('Input'), {
                                modelValue: row.carrierServiceCode,
                                "onOn-blur":(e) => {
                                    row.carrierServiceCode = e.target.value;
                                    this.serviceListOther[index] = row;
                                    }
                                },
                        )} else {
                          return <div>{row.carrierServiceCode}</div>
                        }
                    },
                    align: 'center',
                },
                {
                    title: "是否需要上传面单",
                    key: "isLabel",
                    render:(h,{row, index})=>{
                        if (this.type !== 'query') {
                            return h(resolveComponent('Checkbox'), {
                                modelValue: row.isLabel || false,
                                "onOn-change":(event) => {
                                    row.isLabel = event;
                                    this.serviceListOther[index] = row;
                                    }
                                },
                        )} else {
                          return <div>{row.isLabel ? '是' : '否'}</div>
                        }
                    },
                    align: 'center',
                },
            ]
        },
        logcolumn(){
            return [
                {
                    title: this.$ct('global.common.operate_time',{defaultValue:'操作时间'}),
                    key: 'updatedAt',
                },
                {
                    title: this.$ct('global.common.operator',{defaultValue:'操作人'}),
                    key: 'updatedName',
                },
                {
                    title: this.$ct('global.common.operate_type',{defaultValue:'操作类型'}),
                    render:(h,{row})=>{
                        return this.getLogActions[row.operateType] || '--';
                    }
                },
                {
                    title: "备注",
                    key: 'remark',
                },
            ]
        }
	},
	methods: {
        closemodalprops(){
            this.modalProps = {};
            this.$emit('on-openCloseable');
        },
        changeLabel(){
            this.formData.organizationId = '';
            this.formData.serviceRefCode = '';
        },
        changeBillType(){
            this.formData.thirdPartyAccount = '';
            this.formData.billThirdPartyCountry = '';
            this.formData.billThirdPartyPostal = '';
        },
        addOtherService(){
            this.serviceListOther.push({carrierServiceCode: '', isLabel: false})
        },
        handleChooseService(val){
            this.chooseServiceList = val.map(item=>item.carrierServiceCode)
            this.serviceList.map(item=>{
                if(this.chooseServiceList.indexOf(item.carrierServiceCode) >=0 ){
                    item._checked = true
                }else{
                    item._checked = false
                }
            })
        },
        addAddress(){
            // var url = this.$router.resolve({
            //         name: 'tmsShippingAddressUpdate',
            //         params: { type: 'add' },
            //     });
            //     window.open(url.href, '_blank');
            this.$emit('on-closeCloseable');
            this.modalProps = {
				show: true,
				width: 1000,
				title: "添加发货地址",
				component: "compAddress",
                from: 'logisticsProducts',
				showFooter: false,
				on: {
					"on-success": () => {
						this.modalProps = {};
                        this.getShipCodeList();
                        // this.getDetail()
					}
				}
			}
        },
		onCancel() {
			this.$router.push({
				name: "tmsLogisticsProductsList"
			});
		},
        getServiceList(){
            HttpSysCarrierServiceList({'search[EQ_carrierId]': this.carrierId, 'search[EQ_active]': 1}).then(res=>{
                this.serviceList = res.data;
            },err => {
				this.$Message.error(err.message);
			})
        },
        getShipCodeList(){
            if(this.formData.organizationId)
            HttpShipCodeList({active: 1, contextId: this.formData.organizationId}).then(res => {
                this.shipCodeList = res.data.map(item=>{
                    return {label: item.code, value: item.code, attach: item}
                });
			}, err => {
				this.$Message.error(err.message);
			})
        },
		getDetail() {
			if (this.type === "add" ) {
                this.formData.carrierCode = this.$route.query.carrier;
                this.formData.serviceCode = this.$route.query.code;
                this.formData.carrierGroupId = this.$route.query.carrierGroupId;
                this.getServiceList();
                return;
            }
			this.loading = true;
			HttpCarrierAccountDetail({
				id: this.id,
			}).then(res => {
                this.formData = res.data;
                this.formData.serviceCode = res.data.carrierGroupCode;
                if(res.data.serviceType == 2){
                    this.formData.serviceType = 1;
                }
                if(this.formData.serviceType == 0){
                    let name = this.chooseOrgList.find(item=>item.value == res.data.organizationId);
                    this.formData.orgName = name? name.label : '--';
                }
                this.getShipCodeList();
                this.opLogList = res.data.orderLogsEntityList;
                if(this.isOther){
                    this.serviceListOther = res.data.sysCarrierGroupServiceEntityList.map(item=>{
                        return {...item, isLabel: item.isLabel == 1 ? true : false, }
                    });
                }else{
                    let name = this.accountList.find(item=>item.value == res.data.accountId);
                    // this.formData.accountName = this.accountList.find(item=>item.value == res.data.accountId).label;
                    this.formData.accountName = name ? name.label: '--'
                    if(this.type == 'query'){
                        this.serviceList = res.data.sysCarrierGroupServiceEntityList.filter(item=>item.active == 1).map(item=>{
                            return {...item, isCalculate: item.isCalculate == 1 ? true : false, }
                        });
                    }else{
                        this.chooseServiceList = res.data.sysCarrierGroupServiceEntityList.filter(item=>item.active == 1).map(item=>item.carrierServiceCode)
                        this.serviceList = res.data.sysCarrierGroupServiceEntityList.map(item=>{
                            return {...item, isCalculate: item.isCalculate == 1 ? true : false, }
                        });
                        this.serviceList.map(item=>{
                            if(this.chooseServiceList.indexOf(item.carrierServiceCode) >=0 ){
                                item._checked = true
                            }else{
                                item._checked = false
                            }
                        })
                    }
                }
                this.loading = false;
			}, err => {
				this.loading = false;
				this.$Message.error(err.message);
			});
		},
		async submit() {
            let valid = await this.$refs['form'].validate();
            if (!valid) return;
            let chooseList = [];
            if(!this.isOther){
                this.serviceList.map(item=>{
                    if(this.chooseServiceList.indexOf(item.carrierServiceCode) >=0 ){
                        chooseList.push({carrierServiceCode: item.carrierServiceCode, isCalculate: item.isCalculate == true ? 1: 0, volumeWeight: item.volumeWeight})
                    }
                })
            } else{
                chooseList = this.serviceListOther.map(item=>{
                    return {carrierServiceCode: item.carrierServiceCode, isLabel: item.isLabel == true ? 1: 0}
                })
            }
			this.loading = true;
			HttpCarrierAccountSave({
                ...this.formData,
                hostOrgId: global.SYSID,
                sysCarrierGroupServiceEntityList: chooseList,
			}).then(res => {
				this.loading = false;
                this.$Message.success(res.message)
				this.onCancel();
			}, err => {
				this.loading = false;
				this.$Message.error(err.message);
			})
		},
	}
};
</script>
